import torch
from torch.nn import Embedding
from torch.utils.data import DataLoader
from torch_geometric.nn import GCNConv
from torch_sparse import SparseTensor
from torch_geometric.utils.num_nodes import maybe_num_nodes

from Model.Module.GCN import GCN

try:
    import torch_cluster  # noqa
    random_walk = torch.ops.torch_cluster.random_walk
except ImportError:
    random_walk = None

EPS = 1e-15

class Gcnconv2(torch.nn.Module):

    def __init__(self, edge_index, **kwargs):
        super(Gcnconv2, self).__init__()

        if random_walk is None:
            raise ImportError('`Node2vecGcn` requires `torch-cluster`.')

        N = maybe_num_nodes(edge_index, kwargs['num_nodes'])
        row, col = edge_index
        self.adj = SparseTensor(row=row, col=col, sparse_sizes=(N, N))
        self.adj = self.adj.to('cpu')

        assert kwargs['walk_length'] >= kwargs['context_size']

        self.embedding_dim = kwargs['model_out_layer']
        self.walk_length = kwargs['walk_length'] - 1
        self.context_size = kwargs['context_size']
        self.walks_per_node =  kwargs['walks_per_node']
        self.p =  kwargs['p']
        self.q =  kwargs['q']
        self.num_negative_samples =  kwargs['num_negative_samples']
        # self.num_features=num_features
        # self.embedding = GCNConv(num_features, embedding_dim)
        self.embedding=GCN(kwargs['num_features'], kwargs['model_hideen_layer'], kwargs['model_out_layer'])
        # self.embedding = Embedding(N, embedding_dim, sparse=sparse)
        # self.reset_parameters()

    def reset_parameters(self):
        self.embedding.reset_parameters()

    # def forward(self, batch=None):
    #     """Returns the embeddings for the nodes in :obj:`batch`."""
    #     emb = self.embedding.weight
    #     return emb if batch is None else emb[batch]

    def forward(self, x, edge_index, edge_attr):
        x = self.embedding(x, edge_index,edge_attr)
        return x

    def loader(self, **kwargs):
        return DataLoader(range(self.adj.sparse_size(0)),
                          collate_fn=self.sample, **kwargs)

    def pos_sample(self, batch):
        batch = batch.repeat(self.walks_per_node)
        rowptr, col, _ = self.adj.csr()
        rw = random_walk(rowptr, col, batch, self.walk_length, self.p, self.q)
        if not isinstance(rw, torch.Tensor):
            rw = rw[0]

        walks = []
        num_walks_per_rw = 1 + self.walk_length + 1 - self.context_size
        for j in range(num_walks_per_rw):
            walks.append(rw[:, j:j + self.context_size])
        return torch.cat(walks, dim=0)

    def neg_sample(self, batch):
        batch = batch.repeat(self.walks_per_node * self.num_negative_samples)

        rw = torch.randint(self.adj.sparse_size(0),
                           (batch.size(0), self.walk_length))
        rw = torch.cat([batch.view(-1, 1), rw], dim=-1)

        walks = []
        num_walks_per_rw = 1 + self.walk_length + 1 - self.context_size
        for j in range(num_walks_per_rw):
            walks.append(rw[:, j:j + self.context_size])
        return torch.cat(walks, dim=0)

    def sample(self, batch):
        if not isinstance(batch, torch.Tensor):
            batch = torch.tensor(batch)
        return self.pos_sample(batch), self.neg_sample(batch)

    def loss(self, embedding,pos_rw, neg_rw):
        r"""Computes the loss given positive and negative random walks."""

        # Positive loss.
        start, rest = pos_rw[:, 0], pos_rw[:, 1:].contiguous()
        '''
        embedding没有归一化需要修改
        
        '''
        h_start = embedding[start].view(pos_rw.size(0), 1,self.embedding_dim)
        h_rest = embedding[rest.view(-1)].view(pos_rw.size(0), -1, self.embedding_dim)

        out = (h_start * h_rest).sum(dim=-1).view(-1)
        pos_loss = -torch.log(torch.sigmoid(out) + EPS).mean()

        # Negative loss.
        start, rest = neg_rw[:, 0], neg_rw[:, 1:].contiguous()

        h_start = embedding[start].view(neg_rw.size(0), 1,
                                             self.embedding_dim)
        h_rest = embedding[rest.view(-1)].view(neg_rw.size(0), -1,
                                                    self.embedding_dim)

        out = (h_start * h_rest).sum(dim=-1).view(-1)
        neg_loss = -torch.log(1 - torch.sigmoid(out) + EPS).mean()
        return pos_loss + neg_loss

    def __repr__(self):
        return '{}({}, {})'.format(self.__class__.__name__,
                                   self.embedding.weight.size(0),
                                   self.embedding.weight.size(1))
